package io.yunho.yunho.interview.two.threadlocal;

import java.util.concurrent.TimeUnit;

/**
 * @author: Jason
 * @date: 2021/4/27 16:29
 * @description:
 */
public class ThreadLocalTest {
    static class ResourceUtil{
        private static ThreadLocal<String> RESOURCE_1 = new ThreadLocal<>();
        public static ThreadLocal<String> getThreadLocal(){
            return RESOURCE_1;
        }
        public static void setThreadLocal(ThreadLocal<String> RESOURCE){
            RESOURCE_1 = RESOURCE;
        }

    }
    static class A{
        private String instanceVal;
        public void setTL(String value){
            System.out.println("["+Thread.currentThread().getName()+"]"+" setTL:"+value);
            ResourceUtil.RESOURCE_1.set(value);
        }
        public String getTL(){
            String value = ResourceUtil.RESOURCE_1.get();
            System.out.println("["+Thread.currentThread().getName()+"]"+" getTL:"+value);
            return value;
        }

        public String getInstanceVal() {
            System.out.println("["+Thread.currentThread().getName()+"]"+" getInstanceVal:"+instanceVal);
            return instanceVal;
        }

        public void setInstanceVal(String instanceVal) {
            System.out.println("["+Thread.currentThread().getName()+"]"+" setInstanceVal:"+instanceVal);
            this.instanceVal = instanceVal;
        }
    }

    public static void main(String[] args) {
//        final  A a = new A();
//        for(int i=0;i<3;i++){
//            final String val = " value = ("+i+")";
//            new Thread(()->{
//                try {
//                System.out.println("");
//                a.setTL(val);
//                a.setInstanceVal(val);
//                System.out.println("------------------set over---------------------");
//
//                    TimeUnit.SECONDS.sleep(5);
//                System.out.println("------------------sleep over---------------------");
//                a.getTL();
//                a.getInstanceVal();
//                } catch (InterruptedException e) {e.printStackTrace();}finally {
//                    ResourceUtil.RESOURCE_1.remove();
//                }
//
//            },"threadName--"+String.valueOf(i)).start();
//        }

        try {
            ResourceUtil.RESOURCE_1.set("aa");
            System.out.println(ResourceUtil.RESOURCE_1);
            System.out.println(ResourceUtil.RESOURCE_1.get());
            System.out.println(Thread.currentThread().getName());
            ResourceUtil.RESOURCE_1 = null;
            ResourceUtil.RESOURCE_1 = new ThreadLocal<>();
            System.out.println(ResourceUtil.RESOURCE_1);
            System.out.println(ResourceUtil.RESOURCE_1.get());
            System.out.println(Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(3);

        } catch (InterruptedException e) {e.printStackTrace();}finally {

        }
    }
}

